// pages/issue/todo/todoform.js
const app = getApp();
const path = app.globalData.path;
Page({
  /**
   * Page initial data
   */
  data: {
    issueId: null,
    todolistData: [],
    issueInfo: '',
    path: [],
    imgs: [],
    upload_picture_list: [],
    buttonStatus: '点击显示',
    buttonStatusCls: 'hidden',
    issuePicList: [{
      path: 'http://localhost:8080/pdms/com/image!downloadCmImage.action?id=E0A6F5E149054FB5B75E72E3554AA90F'
    }]
    //resoIndex:0,
    //resoUserIndex:0
    // lifecycleStatus:"",
    // processStatus:""
  },
  // 预览图片
  previewImg(e) {
    console.log(e);
    //获取当前图片的下标
    let index = e.currentTarget.dataset.index;
    console.log(index);
    //所有图片
    let imgs = this.data.picList;
    let imgPaths = [];
    for (var i = 0; i < imgs.length; i++) {
      imgPaths.push(imgs[i].path);
    }
    wx.previewImage({
      //当前显示图片
      current: imgs[index].path,
      //所有图片
      urls: imgPaths
    })
  },
  uploadpic: function(e) {
    //   console.log(that.data.sourceId);
    var that = this;
    let pic_list = that.data.picList;
    let imgs = that.data.imgs
    var uploadUrl = path + 'wx-com/image!uploadCmImage.action'
    let loginFlag = wx.getStorageSync('token');
    wx.chooseImage({
      count: 8, // 默认9，这里显示一次选择相册的图片数量 
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片 
        // console.log(res);
        var tempFiles = res.tempFiles
        //把选择的图片 添加到集合里
        for (let i in tempFiles) {
          tempFiles[i]['upload_percent'] = 0
          tempFiles[i]['path_server'] = ''
          imgs.push(tempFiles[i].path);
          //  console.log(imgs);
          //upload_file_server(uploadUrl,that,tempFiles,that.data.sourceId,i,loginFlag)
          wx.showLoading({
            title: '正在上传....',
          })
          wx.uploadFile({
            // 模拟https
            url: uploadUrl, //需要用HTTPS，同时在微信公众平台后台添加服务器地址  
            filePath: tempFiles[i].path, //上传的文件本地地址    
            name: 'upload',
            header: {
              'token': loginFlag
            },
            formData: {
              'num': i,
              'source': 'QIM_ISSUE_IMAGE',
              'sourceId': that.data.issueId
            },
            //附近数据，这里为路径     
            success: function(res) {
              //   console.log(res);
              var result = JSON.parse(res.data);
              //   console.log(result);
              tempFiles[i].imageId = result.data.id;
              // //字符串转化为JSON  
              console.log("--------------");
              //   console.log(tempFiles);
              pic_list.push(tempFiles[i])
              // if (data.Success == true) {
              //   var filename = data.file //存储地址 显示
              //   tempFiles[i]['path_server'] = filename
              // } else {
              //   tempFiles[i]['path_server'] = filename
              // }
              that.setData({
                picList: pic_list
              });
              wx.hideLoading();
              //wx.setStorageSync('imgs', upload_picture_list);
            }
          })
        }
        console.log(that.data.upload_picture_list);
        //显示
        // that.setData({
        //   upload_picture_list: pic_list,
        //   imgs: imgs
        // });
      }
    })

  },

  // 点击删除图片
  deleteImg(e) {
    let picList = this.data.picList;
    let index = e.currentTarget.dataset.index;
    console.log(index);
    wx.showToast({
      title: '删除中...',
    })
    var loginFlag = wx.getStorageSync('token');
    // var imageUrl = picList[index];
    // var imageId = imageUrl.substring(imageUrl.indexOf("=") + 1);
    // console.log(imageId)
    // 用索引获取list中图片对象  从对象中取出 上传图片时存入的imageId 然后用imageId 从数据库中删除图片。
    wx.request({
      url: path + "wx-com/image!deleteCmImage.action",
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        id: picList[index].imageId
      },
      success: function(res) {
        wx.hideToast();
      },
      fail: function(res) {
        console.log(res);
      }
    })
    picList.splice(index, 1);
    this.setData({
      picList: picList
    });
  },
  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      lifecycleStatus: options.lifecycleStatus,
      processStatus: options.processStatus,
      issueId: options.issueId,
      programVehicleId: options.programVehicleId
    })
    let loginFlag = wx.getStorageSync('token');
    if (loginFlag) { // 检查 session_key 是否过期
      wx.checkSession({ // session_key 有效(未过期)
        success: function() {
          // 查询问题信息
          wx.request({
            url: path + 'wx-issue/q-iissue!getQIIssueInfo.action',
            header: {
              'token': loginFlag
            },
            data: {
              issueId: options.issueId
            },
            dataType: "JSON",
            success: function(res) {
              // console.log(res);
              var result = JSON.parse(res.data);
              // console.log(result.data);
              that.setData({
                issueInfo: result.data
              })
              // 
              that.getPartTypeName(result, loginFlag, that);
              that.getIssueTitle(result, loginFlag, that);
              that.getIssueTypeTitle(result, loginFlag, that);
            },
            fail: function() {
              console.log("fail");
            }
          })
          // 查询责任领域  传入车型
          wx.request({
            url: path + 'wx-pm/project-open-issue!getResponsibleObsList.action',
            header: {
              'token': loginFlag
            },
            data: {
              programVehicleId: options.programVehicleId
            },
            dataType: "JSON",
            success: function(res) {
              // console.log(res);
              var result = JSON.parse(res.data);
              that.setData({
                resoList: result.data
              })
            },
            fail: function() {
              console.log("fail");
            }
          })

          wx.showLoading({
            title: '图片加载中...',
          })

          // 根据sourceId source 查询图片列表
          wx.request({
            url: path + 'wx-com/image!selectCmImageList.action',
            header: {
              'token': loginFlag
            },
            data: {
              sourceId: options.issueId,
              source: 'QIM_ISSUE_IMAGE'
            },
            dataType: "JSON",
            success: function(res) {

              var result = JSON.parse(res.data);
              var picIdList = result.data;
              var picList = [];

              for (var i = 0; i < picIdList.length; i++) {
                var img = {};
                img.imageId = picIdList[i].id;
                img.path = path + 'wx-com/image!downloadCmImage.action?id=' + picIdList[i].id;
                picList.push(img);

              }
              that.setData({
                picList: picList,

              })
              wx.hideLoading();


            },
            fail: function() {
              console.log("fail");
            }
          })
        }
      })
    }
  },
  todoSubmit: function(e, issueId) {
    
    var that = this;
    var data = that.data;
    var issueInfo = data.issueInfo;
    var action = "";

    let loginFlag = wx.getStorageSync('token');
    var model = {};
    let o = e.detail.value;
    var btn = e.detail.target.dataset.btn;
    var approvalAction = "";
    var approvalComment = "这个可以通过了。";
    // model.imgTitle = data.imgs,
    // model.imgSize = [],
    model.createBy = issueInfo.createBy;
    model.createByName = issueInfo.createByName;
    model.createDate = issueInfo.createDate;
    model.customerName = issueInfo.customerName;
    model.subPart = issueInfo.subPart;
    model.issueDescription = issueInfo.issueDescription;
    model.issueLevel = issueInfo.issueLevel;
    model.issuePlanFinishDate = data.date;
    model.issueSourceId = issueInfo.issueSourceId;
    model.issueTypeId = issueInfo.issueTypeId;
    model.lifecycleStatus = issueInfo.lifecycleStatus;
   // model.ownderId = issueInfo.ownerId;
   model.ownerId = that.data.ownerId;
    model.ownerName = data.ownerName;
    model.partTypeId = issueInfo.partTypeId;
    model.productTypes = issueInfo.productTypes;
    model.programCode = issueInfo.programCode;
    model.programId = issueInfo.programId;
    model.programVehicleCode = issueInfo.programVehicleCode;
    model.programVehicleId = issueInfo.programVehicleId;
    model.reportBy = issueInfo.reportBy;
    model.reportByName = issueInfo.reportByName;
    model.reportDate = issueInfo.reportDate;
    model.reportNo = issueInfo.reportNo;
    model.reportOrg = issueInfo.reportOrg;
    model.reportOrgName = issueInfo.reportOrgName;
//  model.responsibleDepartmentName = issueInfo.responsibleDepartmentName;
    model.responsibleDepartmentName = that.data.topDepartmentName;// 责任部门 
    //model.responsibleFunction = issueInfo.responsibleFunction;
   
    model.responsibleFunction = that.data.responsibleFunction;

    model.title = o.title;
   
    if (btn == "SUBMIT") {
      var approvalAction = "Y";
      action = "wx-issue/q-iissue!submitProcess.action";
    } else if (btn == "CANCEL") {
      action = "wx-issue/q-iissue!cancelProcess.action"
    } else if (btn == "REJECT") {
      var approvalAction = "N";
      action = "wx-issue/q-iissue!submitProcess.action";
    } else if (btn == "DELETE") {
      action = "wx-issue/q-iissue!removeIssue.action"
    }

    var url = path + action;
    wx.showLoading({
      title: '加载中,请稍后...',
    })
    wx.request({
      url: url,
      header: {
        'token': loginFlag,
      },
      data: {
        approvalAction: approvalAction,
        approvalComment: approvalComment,
        model: model,
        issueId: data.issueId
      },
      dataType: "JSON",
      success: function() {
        wx.hideLoading();
        wx.showToast({
          title: "成功！",
          icon: 'success', //图标，支持"success"、"loading"，"none" 
          duration: 2000,
          mask: false
        })
        wx.navigateBack({
          success: function() {
            var todo = getCurrentPages()[0];
            todo.onPullDownRefresh();
          }
        });
      },
      fail: function() {
        wx.hideLoading();
      }
    })
  },
  // 提出时间
  dateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  // 责任领域picker Change事件
  resoListChange: function(e) {
    var that = this;
    // var path = getApp().path;
    console.log(e);
    this.setData({
      resoIndex: e.detail.value,
      responsibleFunction: that.data.resoList[e.detail.value].id
    })
    let loginFlag = wx.getStorageSync('token');
    // 查询该责任领域的 责任人
    wx.request({
      url: path + 'wx-pm/project-open-issue!getResponsibleUser.action',
      header: {
        'token': loginFlag
      },
      data: {
        obsId: that.data.resoList[e.detail.value].id
      },
      dataType: "JSON",
      success: function(res) {
        console.log(res);
        var result = JSON.parse(res.data);
        console.log(result.data);
        that.setData({
          resoUserList: result.data
        })
      },
      fail: function() {
        console.log("fail");
      }
    })
  },
  resoUserListChange: function(e) {
    let that = this;
    
    let resoUserIndex = e.detail.value;
    
    this.setData({
      resoUserIndex: resoUserIndex,
      ownerId: that.data.resoUserList[resoUserIndex].id,
      ownerName: that.data.resoUserList[resoUserIndex].name,
      topDepartmentName: that.data.resoUserList[resoUserIndex].topDepartmentName
    })
  },
  getPartTypeName: function(result, loginFlag, that) {
    // 根据问题信息已返回的结果productTypes作为参数 再发送一个request .
    wx.request({
      url: path + 'wx-issue/q-iissue!getPmPartTypeList.action',
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        productTypes: result.data.productTypes
      },
      success: function(r) {
        // console.log(r.data);
        var pmPartTypes = JSON.parse(r.data);
        // 从返回的数据中找到 问题信息 中对应的零件类别  
        // that.setData({
        //   productTypeList: pmPartTypes.data
        // })
        var partArray = pmPartTypes.data;
        var issuePartTypeId = result.data.partTypeId; // 获取问题返回结果中的 partTypeId
        for (var i = 0; i < partArray.length; i++) {
          if (issuePartTypeId == partArray[i].id) {
            that.setData({
              partTypeName: partArray[i].name
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  getIssueTitle: function(result, loginFlag, that) {
    // 根据问题信息已返回的结果 
    wx.request({
      url: path + 'wx-issue/q-iissue!getIssueSourceList.action',
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      success: function(response) {
        var sourceList = JSON.parse(response.data);
        var sourceArray = sourceList.data;
        var issueSourceId = result.data.issueSourceId; // 获取问题信息返回结果中的 issueSourceId
        for (var i = 0; i < sourceArray.length; i++) {
          if (issueSourceId == sourceArray[i].id) {
            that.setData({
              issueSourceTitle: sourceArray[i].title
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  getIssueTypeTitle: function(result, loginFlag, that) {
    var that = this;
    // var path = getApp().path;
    wx.request({
      url: path + 'wx-issue/q-iissue!getIssueTypeList.action',
      //发送的数据
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      //成功回调
      success: function(res) {
        var issueType = JSON.parse(res.data);
        var issueTypeArray = issueType.data;
        var issueTypeId = result.data.issueTypeId;
        for (var i = 0; i < issueTypeArray.length; i++) {
          if (issueTypeId == issueTypeArray[i].id) {
            that.setData({
              issueTypeTitle: issueTypeArray[i].title
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  toggleBtn: function(e) {
    var that = this;
    if (this.data.buttonStatusCls == 'hidden') {
      that.setData({
        buttonStatus: '点击隐藏',
        buttonStatusCls: 'show'
      })
    } else if (this.data.buttonStatusCls == 'show') {
      that.setData({
        buttonStatus: '点击显示',
        buttonStatusCls: 'hidden'
      })
    }
    // var toggleBtnVal = that.data.uhide;
    // console.log(event)
    // var itemId = event.currentTarget.id;
    // if (toggleBtnVal == itemId) {
    //   that.setData({
    //     uhide: 0
    //   })
    // } else {
    //   that.setData({
    //     uhide: itemId
    //   })
    // }
  },
  // bindShowMsg() {
  //   this.setData({
  //     select: !this.data.select
  //   })
  // },
  // mySelect(e) {
  //   var name = e.currentTarget.dataset.name
  //   this.setData({
  //     tihuoWay: name,
  //     select: false
  //   })
  // },
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {},
  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {},
  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {},
  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {},
  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {},
  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {},
  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function() {}
})